package com.example.presentshopping.ui.activity

import android.Manifest
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.transition.Explode
import android.transition.Fade
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.Button
import android.widget.EditText
import androidx.core.app.ActivityCompat
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.bean.SpreadBean
import com.example.presentshopping.config.bean.WaitInfoBean
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.http.HttpURL.Req_myWaitInfo
import com.example.presentshopping.net.http.HttpURL.Req_waitChange
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.tool.GsonUtils
import com.example.presentshopping.utils.tool.ViewSetUtils
import com.permissionx.guolindev.PermissionX
import kotlinx.android.synthetic.main.activity_location.title_main_tv
import kotlinx.android.synthetic.main.activity_spread.*

//我的奖励
class SpreadActivity : BaseMvpActivity() {

    var spreadBean: SpreadBean? = null

    var WaitInfo: WaitInfoBean? = null

    var customizeDialog: AlertDialog.Builder? = null
    var dialog: Dialog? = null


    private var queryInfoPresenter: PublicPresenter? = null

    override val layoutId: Int
        get() = R.layout.activity_spread


    override fun initView(savedInstanceState: Bundle?) {
        title_main_tv.leftBackImageTv.setOnClickListener { finish() }
        queryInfoPresenter = PublicPresenter(this, false, "")
        queryInfoPresenter?.attachView(this)

        queryInfoPresenter?.netWorkRequestPost(HttpURL.Req_myWalletInfo,
            HttpRequest.getGoodsDetail(""))
        iv_share0.setOnClickListener {
            startActivity(Intent(this@SpreadActivity,
                MyearningsActivity().javaClass))
        }  // 我的收益
        iv_share2.setOnClickListener {
            startActivity(Intent(this@SpreadActivity,
                RefundetailActivity().javaClass))
        }  // 退款明细
        iv_share3.setOnClickListener {
            startActivity(Intent(this@SpreadActivity,
                SubsidiaryActivity().javaClass))
        }  // 积分明细
        iv_share.setOnClickListener {
            startActivity(Intent(this@SpreadActivity,
                GiftMoneyActivity().javaClass))
        }  // 礼币明细
        iv_share6.setOnClickListener {
            startActivity(Intent(this@SpreadActivity,
                TeamAwardActivity().javaClass))
        }  //团队收益
        setmyWaitInfo()
        balance_layout_00.setOnClickListener { addSelectedDate() }


    }


    override fun onDestroy() {
        queryInfoPresenter?.detachView()
        super.onDestroy()
    }

    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

    override fun onSuccess(data: String?) {
        spreadBean = GsonUtils.getGson().fromJson(data, SpreadBean().javaClass)
        balance_textview_02.text = spreadBean?.data?.block_currency.toString()
        balance_textview_03.text = spreadBean?.data?.points.toString()


    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    fun addSelectedDate() {
        val mInflater: View
        customizeDialog = AlertDialog.Builder(this)
        mInflater = View.inflate(this, R.layout.wond_selected, null)
        selected(mInflater)
        customizeDialog!!.setView(mInflater)
        customizeDialog!!.create()
        dialog = customizeDialog!!.show()
    }

    fun selected(mInflater: View) {
        val but_liji = mInflater.findViewById<Button>(R.id.but_liji)
        val exieshon = mInflater?.findViewById<EditText>(R.id.exieshon)
        but_liji?.isClickable = false
        exieshon?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //如果第一个数字为0，第二个不为点，就不允许输入
                if (s.toString().startsWith("0") && s.toString().trim().length > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        exieshon.setText(s?.subSequence(0, 1));
                        exieshon.setSelection(1);
                        return;
                    }
                }
                //如果第一为点，直接显示0.
                if (s.toString().startsWith(".")) {
                    exieshon.setText("50.");
                    exieshon.setSelection(2);
                    return
                }

                //限制输入小数位数(2位)
                if (s.toString().contains(".")) {
                    if (s?.length!! - 1 - s.toString().indexOf(".") > 2) {
                        var s = s.toString().subSequence(0, s.toString().indexOf(".") + 2 + 1);
                        exieshon.setText(s);
                        exieshon.setSelection(s.length);
                    }
                }
                Log.e("selected", s.toString())

                if (!TextUtils.isEmpty(s)) {

                        if (s.toString().toDouble() < 50) {
                            but_liji?.setTextColor(Color.parseColor("#c9c9c9"))
                            but_liji?.isClickable = false
                        } else {
                            but_liji?.setTextColor(Color.parseColor("#D10505"))
                            but_liji?.isClickable = true
                        }
                    }
                 else {
                    but_liji?.setTextColor(Color.parseColor("#c9c9c9"))
                    but_liji?.isClickable = false
                }
            }

            override fun afterTextChanged(s: Editable?) {


            }
        })
        but_liji?.setOnClickListener {
            ViewSetUtils.ButtonClickZoomInAnimation(it, 0.90f)
            if (ActivityCompat.checkSelfPermission(
                    context!!,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            ) {
                PermissionX.init(this)
                    .permissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .onExplainRequestReason { scope, deniedList ->
//                        val message = "需要您同意以下权限才能正常使用"
//                        scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
                    }
                    .request { allGranted, grantedList, deniedList ->
                        if (allGranted) {
                            if (!TextUtils.isEmpty(exieshon?.text.toString())) {
                                SerOpsne(exieshon?.text.toString())
                            }
                        } else {

                        }
                    }

            } else {
                if (!TextUtils.isEmpty(exieshon?.text.toString())) {
                    SerOpsne(exieshon?.text.toString())
                }
            }
        }


    }

    fun SerOpsne(amount: String?) {
        queryInfoPresenter?.netWorkRequestPost(Req_waitChange ,HttpRequest.waitChange("amount",amount),object :TaskCallback{
            override fun onSuccess(data: String?) {
                dialog?.dismiss()
                showToast("转入成功")
                setmyWaitInfo()

            }

            override fun onFailure(
                e: Throwable?,
                code: Int,
                msg: String?,
                isNetWorkError: Boolean
            ) {
                dialog?.dismiss()
              showToast(msg)
            }

        })

    }

    fun setmyWaitInfo() {
        queryInfoPresenter?.netWorkRequestGet(Req_myWaitInfo, object : TaskCallback {
            override fun onSuccess(data: String?) {
                WaitInfo = GsonUtils.getGson().fromJson(data, WaitInfoBean().javaClass)
                balance_textview_01.text = WaitInfo?.data?.wait_income
                balance_textview_04.text = WaitInfo?.data?.yestdayTotal
            }

            override fun onFailure(
                e: Throwable?,
                code: Int,
                msg: String?,
                isNetWorkError: Boolean
            ) {

            }


        })
    }

}